import React, {PureComponent} from "react";
import {forEach, isEmpty, isFunction, map} from "lodash-es";
import {isObjectValEqual} from "jh-utils";
import {Table} from 'antd'

/**
 * 合计行
 */
export default class SumRow extends PureComponent {

    static getDerivedStateFromProps(nextProps, prevState) {

        if (!isObjectValEqual(nextProps, {
            dataSource: prevState.propData,
        }, ['dataSource'])) {
            return {
                dataSource: nextProps.dataSource || [],
                propData: nextProps.dataSource
            }
        }
        return null;
    }

    constructor(props) {
        super(props);
        this.state = {
            dataSource: props.dataSource || [],
            propData: props.dataSource
        }
    }

    setSumByCol(value, dataIndex) {
        let changed = false;

        const tmpData = map(this.state.dataSource, (dataItem, dataInd) => {

            if (0 === dataInd && dataItem && dataItem[dataIndex] !== value) {
                changed = true;

                let tmpO = {...dataItem};
                tmpO[dataIndex] = value;
                return tmpO;

            } else {
                return dataItem;
            }
        });

        if (changed) {
            // console.log('setSumByCol changed', value, dataIndex);
            this.setState({dataSource: tmpData});
        }
    }

    render() {
        const {columns, rowSelect} = this.props;
        const {dataSource} = this.state;

        return (
            map(dataSource, (dataItem, rowInd) => (
                <Table.Summary.Row key={rowInd}>
                    {
                        rowSelect && <Table.Summary.Cell index={0}/>
                    }
                    {
                        columns.map((col, index) => {
                            const {dataIndex, align, render} = col;
                            let tdProps = {
                                className: align ? `t-c-${align}` : ''
                            };
                            let showContent = isFunction(render) ? render(
                                dataItem[dataIndex], dataItem, rowInd, dataSource
                            ) : dataItem[dataIndex];
                            let cellIndex = rowSelect ? index + 1 : index;

                            if (0 === index) {
                                return <Table.Summary.Cell key={index}
                                                           index={cellIndex} {...tdProps}>{showContent}</Table.Summary.Cell>
                            } else {
                                return <Table.Summary.Cell key={index}
                                                           index={cellIndex} {...tdProps}>{showContent}</Table.Summary.Cell>
                            }
                        })
                    }
                </Table.Summary.Row>
            ))
        )
    }
}
